<template>
    <div class="course-list flex flex-col sm:flex-row dark:bg-regal-dark w-full">
        <div :class="'w-full ml-0 sm:ml-2 mt-2 sm:mt-0' ">
            <Search :search="search" :reset="reset">
                <template v-slot:body>
                    <el-form-item label="创建日期">
                        <el-date-picker
                            v-model="timeArr"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            format="YYYY/MM/DD"
                            value-format="YYYY-MM-DD"
                        />
                    </el-form-item>
                    <el-form-item label="用户名">
                        <el-select v-model="query.user_id" placeholder="请选择" style="width: 100px">
                            <el-option v-for="item in customerList" :key="item.id" :label="item.username" :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="老师名">
                        <el-select v-model="query.teacher_id" placeholder="请选择" style="width: 100px">
                            <el-option v-for="item in lessonConfig.teacherList" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="课时类型">
                        <el-select v-model="query.lesson_type" placeholder="请选择" style="width: 120px">
                            <el-option v-for="item in lessonConfig.lessonType" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="课时状态">
                        <el-select
                            v-model="query.lesson_status"
                            placeholder="请选择"
                            style="width: 120px"
                        >
                            <el-option
                                v-for="item in lessonConfig.lessonStatus"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            />
                        </el-select>
                    </el-form-item>
                </template>
            </Search>
            <div class="table-default">
                <div class="pt-5 pl-2">
                    <el-button type="primary" @click="addLessonHours">
                        <Icon name="plus" className="w-4 h-4 mr-1" />
                        添加课时
                    </el-button>
                </div>

                <el-table
                    :data="tableData"
                    class="course-table mt-3"
                    border
                    style="width: 100%;height: calc(100% - 100px);"
                >
                    <el-table-column
                        v-for="item in headerConfig"
                        :key="item.prop"
                        :prop="item.prop"
                        :label="item.label"
                    >
                    </el-table-column>
                    <el-table-column label="操作">
                        <template #default="scope">
                            <el-button type="text":disabled="scope.row.lesson_status != 2 && userStore.getId == 1" @click="handleCheck(scope.row)">审核</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination class="mt-3" background layout="prev, pager, next" @current-change="changePage" @size-change="changeLimit"  :current-page="Pages.current_page" :page-sizes="Pages.per_page" :total="Pages.total" />
            </div>

            <el-dialog v-model="visible" title="添加课时" destroy-on-close>
                <div class="edit-dialog">
                    <el-form :label-width="140" :model="form" ref="formRef" :rules="rules">
                        <el-form-item label="用户名" prop="user_id">
                            <el-select v-model="form.user_id">
                                <el-option
                                    v-for="item in customerList"
                                    :key="item.id"
                                    :label="item.username"
                                    :value="item.id"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="老师名" prop="teacher_id" v-if="userStore.getId == 1">
                            <el-select v-model="form.teacher_id">
                                <el-option
                                    v-for="item in lessonConfig.teacherList"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="课时类型" prop="lesson_type">
                            <el-select v-model="form.lesson_type">
                                <template v-for="item in lessonConfig.lessonType">
                                <el-option
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                    v-if="item.name != '预约课时'"
                                />
                                </template>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="课时" prop="hour">
                            <el-input-number v-model="form.hour" controls-position="right" :min="1"  :max="999" />
                            分钟
                        </el-form-item>

                        <el-form-item label="付款截图">
                            <el-upload
                                v-model:file-list="fileList"
                                action="http://192.168.1.8:9999/api/configuration/upload"
                                list-type="picture-card"
                                :on-preview="handlePictureCardPreview"
                                :on-remove="handleRemove"
                            >
                                <el-icon>
                                    <Plus />
                                </el-icon>
                            </el-upload>
                        </el-form-item>
                        <el-form-item label="描述（用户可见）" prop="desc">
                            <el-input v-model="form.desc" placeholder="请输入" />
                        </el-form-item>
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="form.remark" type="textarea" :rows="4" placeholder="请输入内容" />
                        </el-form-item>
                    </el-form>
                </div>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="visible = false">取消</el-button>
                        <el-button type="primary" @click="confirm">
                            确定
                        </el-button>
                    </div>
                </template>
            </el-dialog>
            <el-dialog v-model="checkDialog" title="审核课时" :width="500">
                <div class="check-title">
                    是否通过该课时审核？
                </div>
                <div class="check-content">
                    <el-button type="primary" size="large" @click="check(1)">通过</el-button>
                    <el-button type="danger" size="large" @click="check(2)">驳回</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, nextTick } from 'vue'
import { ElMessage, ElMessageBox, type UploadProps, type UploadUserFile } from 'element-plus'
import { Code } from '/admin/enum/app'
import Message from '/admin/support/message'
import { Plus } from '@element-plus/icons-vue'
import Http from '/admin/support/http'
import { useUserStore} from '/admin/stores/modules/user'
import router from '/admin/router'

const userStore =  useUserStore()
console.log(userStore.getTeacherId, 'user')
// 日历table 的头部配置
const headerConfig = [
    {
        prop: 'customer_name',
        label: '用户名',
    },
    {
        prop: 'lessons',
        label: '课时 / 分钟',
    },
    {
        prop: 'lesson_type_text',
        label: '课时类型',
    },
    {
        prop: 'lesson_status_text',
        label: '课时状态',
    },
    {
        prop: 'remark',
        label: '备注',
    },
    {
        prop: 'teacher_name',
        label: '老师名',
    },
    {
        prop: 'created_at',
        label: '创建时间',
    },
]
const tableData = ref([])
const visible = ref(false)
const query = ref({
    user_id: '',
    teacher_id: '',
    lesson_type: '',
    lesson_status: '',
    start_time: '',
    end_time: '',
})
const checkDialog = ref(false)
const timeArr = ref([])

const form = ref({
    user_id: '',
    teacher_id: userStore.getId == 1 ? '' : userStore.getTeacherId,
    lesson_type: '',
    hour: 30,
    desc: '',
    remark: '',
    pay_images: '',
})
const rules = ref({
    user_id: [
        { required: true, message: '请选择用户名', trigger: 'change' },
    ],
    teacher_id: [
        { required: true, message: '请选择老师名', trigger: 'change' },
    ],
    lesson_type: [
        { required: true, message: '请选择课时类型', trigger: 'change' },
    ],
    hour: [
        { required: true, message: '请输入课时', trigger: 'change' },
    ],
    desc: [
        { required: true, message: '请输入描述', trigger: 'change' },
    ],
})
const formRef = ref(null)

const fileList = ref<UploadUserFile[]>([])

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const lessonConfig = ref({})

const checkData = ref({
    id: '',
    status: 0,
})

const reset = () => {
    query.value = {
        user_id: '',
        teacher_id: '',
        lesson_type: '',
        lesson_status: '',
        start_time: '',
        end_time: '',
    }
    timeArr.value = []
    Pages.current_page = 1
    search()
}
const addLessonHours = () => {
    visible.value = true
    form.value = {
        user_id: '',
        teacher_id: userStore.getId == 1 ? '' : userStore.getTeacherId,
        lesson_type: '',
        hour: 30,
        desc: '',
        remark: '',
        pay_images: '',
    }
    fileList.value = []
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
}
//获取基础配置
const getLessonConfig = async () => {
    const { data } = await Http.get('/lessonHour/lessonConfig')
    if (data.code === Code.SUCCESS) {
        lessonConfig.value = data.data
        search()
    } else {
        Message.error(data.message)
    }
}
//获取所有客户列表
const customerList = ref([])
const getCustomerList = async () => {
    const { data } = await Http.get('/lessonHour/customerList')
    if (data.code === Code.SUCCESS) {
        customerList.value = data.data
    } else {
        Message.error(data.message)
    }
}
//新增课时
const confirm = () => {
    formRef.value.validate((valid: boolean) => {
        if (valid) {
            const params = {
                user_id: form.value.user_id,
                teacher_id: form.value.teacher_id,
                lesson_type: form.value.lesson_type,
                hour: form.value.hour,
                desc: form.value.desc,
                remark: form.value.remark,
                pay_images: fileList.value.map((item) => item.url).join(','),
            }
            Http.post('/lessonHour/add', params)
                .then(r => {
                    if (r.data.code === Code.SUCCESS) {
                        visible.value = false
                        search()
                        Message.success('添加成功')

                    } else {
                        Message.error(r.data.message)
                    }
                })
                .finally(() => {
                })

        } else {
            console.log('error submit!!')
            return false
        }
    })
}
const handleCheck = (row: any) => {
    checkData.value.id = row.id
    checkDialog.value = true
}
//审核课时
const check = async (status:number) => {
    checkData.value.status = status
    let res = await http.post('/lessonHour/check', checkData.value)
    if (res.data.code === Code.SUCCESS) {
        search()
        checkDialog.value = false
        Message.success('审核成功')
    } else {
        Message.error(res.data.message)
    }
}

const Pages = {
    current_page: 1,
    per_page: 10,
    total: 0
}

const changePage = (val: number) => {
    Pages.current_page = val
    search()
}

const changeLimit = (val: number) => {
    Pages.per_page = val
    search()
}

// 获取课时列表
const search = async () => {
    const params = {
        user_id: query.value.user_id,
        teacher_id: query.value.teacher_id,
        lesson_type: query.value.lesson_type,
        lesson_status: query.value.lesson_status,
        page: Pages.current_page,
        limit: Pages.per_page
    }

    if (timeArr.value.length) {
        params.start_time = timeArr.value[0] + ' 00:00:00'
        params.end_time = timeArr.value[1] + ' 23:59:59'
    }
    const { data } = await Http.get('/lessonHour/list', params)
    if (data.code === Code.SUCCESS) {
        tableData.value = data.data.map((item: any) => {
            console.log(item   , 'item')
            item.lesson_status_text = lessonConfig.value.lessonStatus.find((status: any) => status.id == item.lesson_status)?.name
            item.lesson_type_text = lessonConfig.value.lessonType.find((type: any) => type.id == item.lesson_type)?.name
            return item
        })
        Pages.total = data.total
    } else {
        Message.error(data.message)
    }
}
getCustomerList()
getLessonConfig()

// 如果路由上面带有参数，就执行搜索
if (router.currentRoute.value.query.customer_id) {
    query.value.user_id = Number(router.currentRoute.value.query.customer_id)
    search()
}
</script>
<style>

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>

<style scoped lang="scss">
.check-title {
    text-align: center;
    font-size: 20px;
    margin-top: 20px;
}
.check-content {
    text-align: center;
    margin-top: 60px;
    padding-bottom: 20px;
}
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.course-list {
    height: calc(100vh - 120px);
}

.table-default {
    height: calc(100% - 120px);
}

.course-table {
    background: #fff;

    .table {
        width: 100%;
        border: 1px solid #ebeef5;
        border-radius: 8px;

        .course-header {
            height: 60px;

            td {
                text-align: center;
                border-right: 1px solid #ebeef5;
                border-bottom: 1px solid #e1e4e8;
            }
        }

        .course-tr {
            border-bottom: 1px solid #e1e4e8;

            .time {
                width: 100px;
                text-align: center;
                border-right: 1px solid #ebeef5;
            }

            .course-item {
                border-right: 1px solid #ebeef5;
                width: calc(100% / 7.6);
                height: 110px;
                padding: 4px;

                .active {
                    height: 100%;
                    color: #7C93C3;
                    background: #DFF5FF;
                    border-radius: 4px;
                    padding: 10px;
                }
            }
        }
    }
}

.edit-dialog {
    padding: 36px;
}
</style>
